//
//  TT_ConversationDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/4/28.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "TT_ConversationDetailViewController.h"

#import "IMKeyWordCheckHelper.h"

#import "MyCustomCell.h"
#import "TTIM_PackageCardCell.h"
#import "TTIM_CouponCardCell.h"
#import "TTIM_CaseCardCell.h"
#import "TTIM_StoreCardCell.h"
#import "TTIM_OrderCardCell.h"
#import "TUIGuestMessageCell.h"
#import "TUIGroupSystemTipMessageCell.h"
#import "TTIM_NotiCardCell.h"

#import "TTIM_StoreInfoModel.h"
#import "TTIM_ServiceModel.h"

#import "TTIM_UserInfoSellerInfoModel.h"
#import "TTIM_ContactHeadView.h"


#import "TUIChatController.h"
#import "TUITextMessageCellData.h"
#import "SearchPackageViewController.h"
#import "StoreDetailViewController.h"

#import "PortfilioDetailViewController.h"
#import "StoreHotelDetailViewController.h"

#import "FieldOrderDetailViewController.h"
#import "SerOrderDetailViewController.h"
#import "ProOrderDetailViewController.h"
#import "TT_GroupUserListViewController.h"
#import "TUIGroupMemberController.h"

#import "TIIMQuickReplyCardView.h"
#import "TIIMQuickReplyCardModel.h"

#import "StoreDetailSubscribeView.h"
#import <LSTPopView/LSTPopView.h>
#import <BRDatePickerView.h>

@interface TT_ConversationDetailViewController ()<TUIChatControllerDelegate,TUIGuestMessageCellDelegate,V2TIMSimpleMsgListener>

@property (nonatomic, strong) TUIChatController *chat;

@property (nonatomic, strong) TTIM_ContactHeadView *headView;

@property (nonatomic, strong) TTIM_StoreInfoModel *storeModel;
@property (nonatomic, strong) TTIM_ServiceModel *serviceModel;



@property(nonatomic,strong)BaseAdjustButton *quickButton;
@property(nonatomic,strong)TIIMQuickReplyCardView *quickCardIV;

@property (nonatomic, weak) LSTPopView *popView;
@end

@implementation TT_ConversationDetailViewController

- (void)dealloc {
    NSLog(@"TT_ConversationDetailViewController - dealloc");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[TT_MessageManager manager] refreshUnReadCount];
    [[V2TIMManager sharedInstance] removeSimpleMsgListener:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[V2TIMManager sharedInstance] addSimpleMsgListener:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self getQuickReplyStatus];
    
    WEAKSELF
    if (self.quickReply.length > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf sendText:weakSelf.quickReply];
        });
    }
}

- (void)initView {
    
    TUIKitConfig *config = [TUIKitConfig defaultConfig];
    // 修改默认头像
    config.defaultAvatarImage = [UIImage imageNamed:@"guide_usericon"];
    config.avatarType = TAvatarTypeRadiusCorner;

    self.chat = [[TUIChatController alloc] initWithConversation:self.conversationData];
//
    self.chat.delegate = self;
    [self addChildViewController:self.chat];
    [self.view addSubview:self.chat.view];
    
    RAC(self, title) = [RACObserve(_conversationData, title) distinctUntilChanged];
    [self checkTitle];

    if (self.conversationData.groupID) {
        [self request_storeId];
    }
    
    if (self.conversationData.userID) {
        
        if ([self.conversationData.userID hasPrefix:@"platform"]) {
            
            [self request_platformType];
        }
    }

    [self configMenu];
    [self configView];
}

- (void)checkTitle {
    if (_conversationData.title.length == 0) {
        if (_conversationData.userID.length > 0) {
            _conversationData.title = _conversationData.userID;
             @weakify(self)
            [[V2TIMManager sharedInstance] getFriendsInfo:@[_conversationData.userID] succ:^(NSArray<V2TIMFriendInfoResult *> *resultList) {
                @strongify(self)
                V2TIMFriendInfoResult *result = resultList.firstObject;
                if (result.friendInfo && result.friendInfo.friendRemark.length > 0) {
                    self.conversationData.title = result.friendInfo.friendRemark;
                } else {
                    [[V2TIMManager sharedInstance] getUsersInfo:@[self.conversationData.userID] succ:^(NSArray<V2TIMUserFullInfo *> *infoList) {
                        V2TIMUserFullInfo *info = infoList.firstObject;
                        if (info && info.nickName.length > 0) {
                            self.conversationData.title = info.nickName;
                        }
                    } fail:nil];
                }
            } fail:nil];
        }
        if (_conversationData.groupID.length > 0) {
            _conversationData.title = _conversationData.groupID;
             @weakify(self)
            [[V2TIMManager sharedInstance] getGroupsInfo:@[_conversationData.groupID] succ:^(NSArray<V2TIMGroupInfoResult *> *groupResultList) {
                @strongify(self)
                V2TIMGroupInfoResult *result = groupResultList.firstObject;
                if (result.info && result.info.groupName.length > 0) {
                    self.conversationData.title = result.info.groupName;
                }
            } fail:nil];
        }
    }
}

//去掉几个不需要的菜单
- (void)configMenu {
    
    NSMutableArray *moreMenus = [NSMutableArray array];
    
    TUIInputMoreCellData *photoData = [TUIInputMoreCellData photoData];
    photoData.image = [UIImage imageNamed:@"im_photo"];
    photoData.title = @"相册";
    [moreMenus addObject:photoData];
    
    TUIInputMoreCellData *pictureData = [TUIInputMoreCellData pictureData];
    pictureData.image = [UIImage imageNamed:@"im_camera"];
    pictureData.title = @"拍照";
    [moreMenus addObject:pictureData];

    self.chat.moreMenus = moreMenus;
}

- (void)configBusinissMenu {
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.chat.moreMenus];
    
    if ([self.storeModel.classId isKindOfClass:[NSString class]] && self.storeModel.classId.length > 0) {
        //初始化一个产品的按钮
        TUIInputMoreCellData *product = [[TUIInputMoreCellData alloc] init];
        product.image = [UIImage imageNamed:@"im_product"];
        product.title = @"套餐";
        [array addObject:product];
    }
    
    if (self.conversationData.groupID.length > 0) {
        TUIInputMoreCellData *groupUser = [[TUIInputMoreCellData alloc] init];
        groupUser.image = [UIImage imageNamed:@"im_groupUser"];
        groupUser.title = @"群成员";
        [array addObject:groupUser];
    }

    self.chat.moreMenus = array;
}

#pragma mark 新消息
//收到新的群消息
- (void)onRecvGroupTextMessage:(NSString *)msgID groupID:(NSString *)groupID sender:(V2TIMGroupMemberInfo *)info text:(NSString *)text {
    if ([groupID isEqualToString:self.conversationData.groupID]) {
        WEAKSELF
        [IMKeyWordCheckHelper checkUserMsg:text comption:^(BOOL success, IMAlertActionType type, NSString * _Nonnull message) {
            if (success) {
                [[TT_AlertManager manager] alertTitle:@"发送方式"
                             message:@"选择你所需发送的联系方式"
                        leftBtnTitle:@"发微信号"
                          leftAction:^{[weakSelf sendWechat];}
                       rightBtnTitle:@"发手机号"
                         rightAction:^{[weakSelf sendPhone];}
                        cancleAction:^{}];
            }
        }];
    }
}

- (void)onRecvC2CTextMessage:(NSString *)msgID  sender:(V2TIMUserInfo *)info text:(NSString *)text {
    if ([info.userID isEqualToString:self.conversationData.userID]) {
        WEAKSELF
        [IMKeyWordCheckHelper checkUserMsg:text comption:^(BOOL success, IMAlertActionType type, NSString * _Nonnull message) {
            if (success) {
                [[TT_AlertManager manager] alertTitle:@"发送方式"
                             message:@"选择你所需发送的联系方式"
                        leftBtnTitle:@"发微信号"
                          leftAction:^{[weakSelf sendWechat];}
                       rightBtnTitle:@"发手机号"
                         rightAction:^{[weakSelf sendPhone];}
                        cancleAction:^{}];
            }
        }];
    }
}

- (TUIMessageCellData *)chatController:(TUIChatController *)controller onNewMessage:(V2TIMMessage *)msg
{
    
    if (msg.elemType == V2TIM_ELEM_TYPE_CUSTOM) {

        NSDictionary *param = [Utilities dicWithData:msg.customElem.data];
        NSLog(@"%@",param);
        if (param != nil) {

            TTIM_CustomMsgModel *model =[TTIM_CustomMsgModel mj_objectWithKeyValues:param];

            switch (model.type) {
                case IM_TIMCustomMsgType_package:{

                    TTIM_PackageCardCellData *cellData = [[TTIM_PackageCardCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.model = model;
                    return cellData;
                } break;
                case IM_TIMCustomMsgType_case:{

                    TTIM_CaseCardCellData *cellData = [[TTIM_CaseCardCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.model = model;
                    return cellData;
                } break;
                case IM_TIMCustomMsgType_coupon:{

                    TTIM_CouponCardCellData *cellData = [[TTIM_CouponCardCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.model = model;
                    return cellData;
                } break;
                case IM_TIMCustomMsgType_store:{

                    TTIM_StoreCardCellData *cellData = [[TTIM_StoreCardCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.model = model;
                    return cellData;
                } break;
                case IM_TIMCustomMsgType_order:{

                    TTIM_OrderCardCellData *cellData = [[TTIM_OrderCardCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.model = model;
                    return cellData;
                } break;
                case IM_TIMCustomMsgType_guest:{

                    TUIGuestMessageCellData *cellData = [[TUIGuestMessageCellData alloc] initWithDirection:msg.isSelf ? MsgDirectionOutgoing : MsgDirectionIncoming];
                    cellData.customModel = [TUICustomModel mj_objectWithKeyValues:param];
                    return cellData;
                } break;
                default:{
                  
                    TUIGroupSystemTipMessageCellData *cellData = [[TUIGroupSystemTipMessageCellData alloc] initWithDirection:MsgDirectionOutgoing];
                    return cellData;
                    
                } break;
            }
        }
    }

    return nil;
}

#pragma mark 自定义消息样式显示
- (TUIMessageCell *)chatController:(TUIChatController *)controller onShowMessageData:(TUIMessageCellData *)data
{
    switch (data.direction) {
        case MsgDirectionOutgoing:{
            data.avatarUrl = [NSURL URLWithString:[TTUserModel sharedObject].userIcon];
//            data.name = [TTUserModel sharedObject].nickname;

        } break;
        case MsgDirectionIncoming:{

            if (self.conversationData.userID.length > 0) {//如果自定义消息发送方都传了头像 这个可以省掉
                [[V2TIMManager sharedInstance] getUsersInfo:@[self.conversationData.userID] succ:^(NSArray<V2TIMUserFullInfo *> *infoList) {
                    data.avatarUrl = [NSURL URLWithString:infoList.firstObject.faceURL];
                } fail:^(int code, NSString *msg) {
                    NSLog(@"拉取用户资料失败！");
                }];
            }

        } break;

        default:
            break;
    }
    if ([data isKindOfClass:[TTIM_PackageCardCellData class]]) {
        TTIM_PackageCardCell *myCell = [[TTIM_PackageCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_PackageCardCellID"];
        [myCell fillWithData:(TTIM_PackageCardCellData *)data];
        return myCell;

    } else if ([data isKindOfClass:[TTIM_CouponCardCellData class]]) {
        TTIM_CouponCardCell *myCell = [[TTIM_CouponCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_CouponCardCellID"];
        [myCell fillWithData:(TTIM_CouponCardCellData *)data];
        return myCell;

    } else if ([data isKindOfClass:[TTIM_CaseCardCellData class]]) {
       TTIM_CaseCardCell *myCell = [[TTIM_CaseCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_CaseCardCellID"];
       [myCell fillWithData:(TTIM_CaseCardCellData *)data];
       return myCell;

    } else if ([data isKindOfClass:[TTIM_StoreCardCellData class]]) {
        TTIM_StoreCardCell *myCell = [[TTIM_StoreCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_StoreCardCellID"];
        [myCell fillWithData:(TTIM_StoreCardCellData *)data];
        return myCell;

     } else if ([data isKindOfClass:[TTIM_OrderCardCellData class]]) {
         TTIM_OrderCardCell *myCell = [[TTIM_OrderCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_OrderCardCellID"];
         [myCell fillWithData:(TTIM_OrderCardCellData *)data];
         return myCell;

      } else if ([data isKindOfClass:[TUIGroupSystemTipMessageCellData class]]) {
          TUIGroupSystemTipMessageCell *myCell = [[TUIGroupSystemTipMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TUIGroupSystemTipMessageCellID"];
          [myCell fillWithData:(TUIGroupSystemTipMessageCellData *)data];
          return myCell;

      } else if ([data isKindOfClass:[TTIM_NotiCellData class]]) {
          TTIM_NotiCardCell *myCell = [[TTIM_NotiCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TTIM_NotiCardCellID"];
          [myCell fillWithData:(TTIM_NotiCellData *)data];
          return myCell;

      } else if ([data isKindOfClass:[TUIGuestMessageCellData class]]) {
          TUIGuestMessageCell *myCell = [[TUIGuestMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TUIGuestMessageCellID"];
          [myCell fillWithData:(TUIGuestMessageCellData *)data];
          myCell.guestDelegate = self;
          return myCell;
      }
    return nil;
}

#pragma mark 自定义消息选中
- (void)chatController:(TUIChatController *)controller onSelectMessageContent:(TUIMessageCell *)cell {
    
    if ([cell isKindOfClass:[TTIM_PackageCardCell class]]) {

        TTIM_PackageCardCellData *cellData = [(TTIM_PackageCardCell *)cell customData];
        NSDictionary *ext = cellData.model.ext;

        IM_CustomPackageModel *model = [IM_CustomPackageModel modelWithDictionary:ext];
        
        CommonPackageModel *packageModel = [[CommonPackageModel alloc] init];
        packageModel.goodsId = model.goodsId;
        packageModel.goodsVersion = model.goodsVersion;
        packageModel.classId = model.classId;
        
        [[TT_JumpManager sharedManager] jumpWithDetailModel:packageModel completion:^(BOOL success, NSString * _Nonnull message) {}];
        
    } else if ([cell isKindOfClass:[TTIM_CouponCardCell class]]) {//优惠券
        
        TTIM_CouponCardCellData *cellData = [(TTIM_CouponCardCell *)cell customData];
        NSDictionary *ext = cellData.model.ext;
        NSString *scoId = [ext valueForKey:@"cuponId"];
        [self request_getCouponWith:scoId];

    } else if ([cell isKindOfClass:[TTIM_CaseCardCell class]]) {//优惠券
           
        TTIM_PackageCardCellData *cellData = [(TTIM_PackageCardCell *)cell customData];
        NSDictionary *ext = cellData.model.ext;

        IM_CustomCaseModel *model = [IM_CustomCaseModel modelWithDictionary:ext];
        PortfilioDetailViewController *vc = [[PortfilioDetailViewController alloc] init];
        vc.soId = model.opusId;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([cell isKindOfClass:[TTIM_StoreCardCell class]]) {//店铺
        
        TTIM_StoreCardCellData *cellData = [(TTIM_StoreCardCell *)cell customData];
        NSDictionary *ext = cellData.model.ext;
        IM_CustomStoreModel *model = [IM_CustomStoreModel modelWithDictionary:ext];
        
        if ([model.classId isEqualToString:Store_Category_Hotel]) {
            
            StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
            vc.storeId = model.sellerId;
            [self.navigationController pushViewController:vc animated:YES];
            
        } else {
            StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
            vc.storeId = model.sellerId;
            [self.navigationController pushViewController:vc animated:YES];
        }

        
    } else if ([cell isKindOfClass:[TTIM_OrderCardCell class]]) {//订单
        
        TTIM_OrderCardCellData *cellData = [(TTIM_OrderCardCell *)cell customData];
        NSDictionary *ext = cellData.model.ext;
        IM_CustomOrderModel *model = [IM_CustomOrderModel modelWithDictionary:ext];
        
        switch (model.orderType) {
            case 1:{
                SerOrderDetailViewController *vc = [[SerOrderDetailViewController alloc] init];
                vc.orderId = model.uoId;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            case 2:{
                ProOrderDetailViewController *vc = [[ProOrderDetailViewController alloc] init];
                vc.orderId = model.uoId;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            case 3:{
                FieldOrderDetailViewController *vc = [[FieldOrderDetailViewController alloc] init];
                vc.orderId = model.uoId;
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            default:
                break;
        }
    }
}

#pragma mark 发送消息回调
- (void)chatController:(TUIChatController *)controller didSendMessage:(TUIMessageCellData *)msgCellData {
    
    [[BA_BusinessHelper shared] clearBrowseData];

    //last msg    check is same day，if no ->request，yes pass
    NSTimeInterval lastMsgTime = [Utilities getTimestampWithDate:self.conversationData.time];
    if ([Utilities isSameDay:lastMsgTime Time2:[Utilities getCurrentTimestamp]]) {
        NSLog(@"同一天");
    } else {
        //隔天了 需要请求接口  只有在群聊的时候请求
//        if (self.conversationData.groupID && self.storeModel.sellerId.length > 0) {
//            [self request_imStoreToSms];//6月3日 王聪 黄石说不要了
//        }
        
        //单聊   统筹师     20点到9点    发短信
        if (self.conversationData.userID && ([Utilities isBetweenFromHour:0 toHour:9] || [Utilities isBetweenFromHour:20 toHour:24])) {
            [self request_imUserToSms];
        }
    }
    
    if (self.conversationData.groupID && self.storeModel.sellerId.length > 0) {
        [self request_imMessage];
    }
    
    //
    if (self.conversationData.userID && [self.conversationData.userID hasPrefix:@"platform"]) {
        [self request_imLisenMessage];
    }
}

#pragma mark 选中了更多按钮
- (void)chatController:(TUIChatController *)chatController onSelectMoreCell:(TUIInputMoreCell *)cell {
    
    if ([cell.title.text isEqualToString:@"套餐"]) {
                
        SearchPackageViewController *vc = [[SearchPackageViewController alloc] init];
        vc.storeId = self.storeModel.sellerId;
        vc.SearchPackageVCBlock = ^(CommonPackageModel * _Nonnull model) {
            //拿到model发消息
        NSLog(@"%@",model.goodsName);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self sendPackageToUser:model];
        });
            
        };
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([cell.title.text isEqualToString:@"群成员"]) {
        TT_GroupUserListViewController *vc = [[TT_GroupUserListViewController alloc] init];
        //TUIGroupMemberController *vc = [[TUIGroupMemberController alloc] init];
        vc.groupId = self.conversationData.groupID;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

#pragma mark 点击了头像
- (void)chatController:(TUIChatController *)controller onSelectMessageAvatar:(TUIMessageCell *)cell {
    
}

#pragma mark 发送套餐
- (void)sendPackageToUser:(CommonPackageModel *)model {

    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *ext = @{}.mutableCopy;
    [dic setValue:@(1) forKey:@"type"];
    [ext setValue:model.fangUrl forKey:@"goodsUrl"];
    [ext setValue:model.goodsName forKey:@"goodsName"];
    [ext setValue:@(model.goodsActivePrice) forKey:@"goodsActivePrice"];
    [ext setValue:model.goodsId forKey:@"goodsId"];
    [dic setValue:ext forKey:@"ext"];

    NSData *data = [Utilities dataWithDic:dic];

    TTIM_PackageCardCellData *cellData = [[TTIM_PackageCardCellData alloc] initWithDirection:MsgDirectionOutgoing];
    cellData.avatarUrl = [NSURL URLWithString:[TTUserModel sharedObject].userIcon];
    cellData.name = [TTUserModel sharedObject].nickname;

    cellData.model = [TTIM_CustomMsgModel modelWithDictionary:dic];

    cellData.innerMessage = [[V2TIMManager sharedInstance] createCustomMessage:data];

    [self.chat sendMessage:cellData];
}

#pragma mark 发送本地信息
//发送平台监管信息
- (void)sendTipMessage {

    //发送平台监管信息
    TUIGroupSystemTipMessageCellData *cellData = [[TUIGroupSystemTipMessageCellData alloc] initWithDirection:MsgDirectionOutgoing];
    NSData *data = [NSData new];
    cellData.innerMessage = [[V2TIMManager sharedInstance] createCustomMessage:data];
    [self.chat sendMessage:cellData];
}

//发送提醒信息
- (void)sendNotiMessage {
    //发送聊天提醒信息
    TTIM_NotiCellData *cellData = [[TTIM_NotiCellData alloc] initWithDirection:MsgDirectionOutgoing];
    NSData *data = [NSData new];
    cellData.innerMessage = [[V2TIMManager sharedInstance] createCustomMessage:data];
    [self.chat sendMessage:cellData];
}

- (void)sendText:(NSString *)text {
    
    TIMTextElem *txt_elem = [[TIMTextElem alloc] init];
    txt_elem.text = text;
    TUITextMessageCellData *cellData = [[TUITextMessageCellData alloc] initWithDirection:MsgDirectionOutgoing];
    cellData.content = text;
    cellData.innerMessage = [[V2TIMManager sharedInstance] createTextMessage:text];
    [self.chat sendMessage:cellData];
}

#pragma mark 业务代码
- (void)goStore {
    
    if (self.storeModel.sellerId.length > 0) {

        if ([self.storeModel.classId isEqualToString:Store_Category_Hotel]) {
            
            StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
            vc.storeId = self.storeModel.sellerId;
            [self.navigationController pushViewController:vc animated:YES];
            
        } else {
            StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
            vc.storeId = self.storeModel.sellerId;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"未获取到店铺id"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (void)goCall {
    TT_GroupUserListViewController *vc = [[TT_GroupUserListViewController alloc] init];
    //TUIGroupMemberController *vc = [[TUIGroupMemberController alloc] init];
    vc.groupId = self.conversationData.groupID;
    [self.navigationController pushViewController:vc animated:YES];
    return;
    if (self.storeModel.sellerId.length > 0) {
        [[TT_PhonaCallManager manager] callWithStoreId:self.storeModel.sellerId];
    } else {
        [SVProgressHUD showErrorWithStatus:@"未获取到店铺id"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (void)configView {
            
    [self.view addSubview:self.headView];
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    [self.chat.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(self.headView.mas_bottom);
    }];
    
    [self initViewAction];
}

- (void)initViewAction {
    
    WEAKSELF
    self.headView.TTIM_ContactHeadViewBlock = ^(TTIM_ContactHeadViewActionType type) {
      
        switch (type) {
            case TTIM_ContactHeadViewActionType_phone:{
                [weakSelf sendPhone];
            } break;
            case TTIM_ContactHeadViewActionType_wechat:{
                [weakSelf sendWechat];
            } break;
            default:
                break;
        }
    };
}

- (void)sendPhone {
    NSString *phone = [NSString stringWithFormat:@"手机号：%@",[TTUserModel sharedObject].username];
    [self sendText:phone];
    if (self.storeModel.sellerId.length > 0 && [TTUserModel sharedObject].username.length > 0) {
        [[BA_BusinessHelper shared] request_updateInfoWithSellerId:self.storeModel.sellerId
                                                           phoneNo:[TTUserModel sharedObject].username
                                                       andWechatId:@""
                                                          comption:^(BOOL success) {}];
    }
}

- (void)sendWechat {
    if (self.storeModel.sellerId.length > 0 && [TTUserModel sharedObject].wechatNo.length > 0) {
        NSString *wx = [NSString stringWithFormat:@"微信号：%@",[TTUserModel sharedObject].wechatNo];
        [self sendText:wx];
        [[BA_BusinessHelper shared] request_updateInfoWithSellerId:self.storeModel.sellerId
                                                           phoneNo:@""
                                                       andWechatId:[TTUserModel sharedObject].wechatNo
                                                          comption:^(BOOL success) {}];
    } else {
        [SVProgressHUD showErrorWithStatus:@"未获取到微信ID，请在‘我的’-‘设置’-‘个人信息'中设置您的微信ID"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (void)configNaviItem {
    
    //go store btn
    UIButton *storeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [storeBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
    [storeBtn setImage:[UIImage imageNamed:@"field_dianpu"] forState:UIControlStateNormal];
    [storeBtn addTarget:self action:@selector(goStore) forControlEvents:UIControlEventTouchUpInside];
    storeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    storeBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *storeItem = [[UIBarButtonItem alloc] initWithCustomView:storeBtn];

    //phone call btn
    UIButton *callBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [callBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
    //[callBtn setImage:[UIImage imageNamed:@"phone"] forState:UIControlStateNormal];
    [callBtn setImage:[UIImage imageNamed:@"im_qunliao"] forState:UIControlStateNormal];
    [callBtn addTarget:self action:@selector(goCall) forControlEvents:UIControlEventTouchUpInside];
    callBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    callBtn.frame = CGRectMake(0,0,40,40);
    UIBarButtonItem *callItem = [[UIBarButtonItem alloc] initWithCustomView:callBtn];
    
    if (self.storeModel.classId.length > 0) {
        self.navigationItem.rightBarButtonItems =@[callItem,storeItem];
    } else {
        self.navigationItem.rightBarButtonItems =@[callItem];
    }
}

- (TTIM_ContactHeadView *)headView {
    if (!_headView) {
        _headView =  [[NSBundle mainBundle] loadNibNamed:@"TTIM_ContactHeadView"owner:nil options:nil].firstObject;
    }
    return _headView;
}

#pragma mark 发消息到短信(store)
- (void)request_imStoreToSms {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.conversationData.groupID forKey:@"groupId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyImToSms];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.conversationData.time = [Utilities getDateWithTimestamp:[Utilities getCurrentTimestamp]];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

- (void)request_imMessage {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.conversationData.groupID forKey:@"groupId"];
    [dic setValue:@"0" forKey:@"isSend"];
    [dic setValue:@"1" forKey:@"type"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyImMessage];
    [TTHttpManager postRequestWithUrl:url
                              TimeOut:10
                             PostData:dic
                          FinishBlock:^(id  _Nonnull data) {}
                          FailedBlock:^(NSError * _Nonnull error) {}];
}

- (void)request_platformType {
    //1、单聊  刚进来   不要传type    给我返回实体   包含了用户客服关系
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:self.conversationData.userID forKey:@"customerServiceId"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyImRdsLisenMessage];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                weakSelf.serviceModel = [TTIM_ServiceModel modelWithJSON:resultDic];
                
                if ([weakSelf.serviceModel.serviceType isEqualToString:@"2"]) {
                    //判断是不是统筹师，如果是的话，弹窗
                    //[Utilities showToast:@"006号人工客服正在为您竭诚服务" FColor:UIColor.whiteColor BColor:[UIColorHex(0x000000) colorWithAlphaComponent:0.7] BLayerColor:UIColor.clearColor];
                    [weakSelf sendNotiMessage];
                }

            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_imLisenMessage {
    //2、发消息服务器监听回调
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:self.conversationData.userID forKey:@"customerServiceId"];
    [dic setValue:self.serviceModel.serviceType forKey:@"serviceType"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyImRdsLisenMessage];
    [TTHttpManager postRequestWithUrl:url
                              TimeOut:10
                             PostData:dic
                          FinishBlock:^(id  _Nonnull data) {}
                          FailedBlock:^(NSError * _Nonnull error) {}];
}


#pragma mark 发消息到短信(user)
- (void)request_imUserToSms {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.conversationData.userID forKey:@"userName"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyImUserToSms];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.conversationData.time = [Utilities getDateWithTimestamp:[Utilities getCurrentTimestamp]];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

#pragma mark 获取店铺Id
- (void)request_storeId {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.conversationData.groupID forKey:@"groupId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_GetIMStoreId];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                weakSelf.storeModel = [TTIM_StoreInfoModel modelWithDictionary:resultDic];

                [weakSelf configBusinissMenu];
                [weakSelf configNaviItem];
                [weakSelf sendTipMessage];
                [weakSelf sendGuestMessage];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

#pragma mark 领取优惠券
- (void)request_getCouponWith:(NSString *)scoId {
    
    WEAKSELF
    [[BA_BusinessHelper shared] callgetCouponWith:scoId And:self.storeModel.sellerId comption:^(BOOL success) {
        if (success) {
            [weakSelf sendText:@"已领取优惠券"];
        }
    }];
}
#pragma mark - 快捷回复模块
- (BaseAdjustButton *)quickButton
{
    if (!_quickButton) {
        BaseAdjustButton *button = [BaseAdjustButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:button];
        button.type = layoutTypeHorizontalLeftImageRightTitle;
        button.imageWidth = 16*ADAPTER_WIDTH;
        button.imageHeight = 17*ADAPTER_WIDTH;
        button.title = @"快捷提问";
        button.fontWeight = UIFontWeightRegular;
        button.fontSize = 14*ADAPTER_WIDTH;
        button.marginLeft = 10*ADAPTER_WIDTH;
        button.marginItemX = 4*ADAPTER_WIDTH;
        button.marginRight = 10*ADAPTER_WIDTH;
        button.marginTop = 5*ADAPTER_WIDTH;
        button.marginBottom = 6*ADAPTER_WIDTH;
        [button begin];
        button.left = WIDTH - button.width - 14*ADAPTER_WIDTH;
        button.backgroundColor = WhiteColor;
        button.layer.cornerRadius = button.height * 0.5;
        button.layer.masksToBounds = YES;
        [button setTitleColor:rgba(85, 85, 85, 1) forState:UIControlStateNormal];
        [button setImage:[UIImage getPNGimageInBundleWithName:@"Chat_quick_?"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickQuickButton:) forControlEvents:UIControlEventTouchUpInside];
        _quickButton = button;
    }
    return _quickButton;
}
- (TIIMQuickReplyCardView *)quickCardIV
{
    if (!_quickCardIV) {
        TIIMQuickReplyCardView *iv = [[TIIMQuickReplyCardView alloc]initWithFrame:CGRectMake(WIDTH - 314*ADAPTER_WIDTH, 0, 304*ADAPTER_WIDTH, 259*ADAPTER_WIDTH)];
        WK(weakSelf)
        [iv setClickFlexButtonBlock:^{
            [weakSelf clickFlexButton:nil];
        }];
        [iv setCallBackContentBlock:^(TIIMQuickReplyCardDataModel * _Nonnull dataModel) {
            [weakSelf sendText:dataModel.content];
            [weakSelf clickFlexButton:nil];
        }];
        _quickCardIV = iv;
    }
    return _quickCardIV;
}
- (void)rACObserveInputController:(TIIMQuickReplyCardModel *)cardModel
{
    self.quickCardIV.hidden = YES;
    self.quickCardIV.cardModel = cardModel;
    
    WEAKSELF
    [RACObserve(self.chat.inputController.view, frame) subscribeNext:^(id x) {
        weakSelf.quickButton.bottom = weakSelf.chat.inputController.view.top + 40*ADAPTER_WIDTH;
        if (weakSelf.quickCardIV.alpha > 0) {
            weakSelf.quickCardIV.bottom = weakSelf.quickButton.top - 4*ADAPTER_WIDTH;
        }
    }];
    
    //暂时不主动弹出
    if (self.quickReply.length == 0) {
        //[self clickQuickButton:nil];
    }
}
- (void)getQuickReplyStatus
{
    //获取快捷回复
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (self.conversationData.groupID.length > 0) {
        [parameters setValue:self.conversationData.groupID forKey:@"groudId"];
    }
    if (self.conversationData.userID.length > 0) {
        [parameters setValue:self.conversationData.userID forKey:@"userName"];
    }
    WK(weakSelf)
    [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/userProblem/userSelectList"] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
        //NSLog(@"%@",responseObject);
        TIIMQuickReplyCardModel *responModel = [TIIMQuickReplyCardModel modelWithJSON:responseObject];
        if (responModel.success) {
            if (responModel.data.count > 0) {
                [weakSelf rACObserveInputController:responModel];
            }
        } else {
            
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}
- (void)clickQuickButton:sender
{
    if (self.quickCardIV.isHidden) {
        [self.view insertSubview:self.quickCardIV belowSubview:self.headView];
        self.quickCardIV.bottom = self.quickButton.top - 4*ADAPTER_WIDTH;
        self.quickCardIV.hidden = NO;
        WK(weakSelf)
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.quickCardIV.alpha = 1.0f;
        }];
    } else {
        [self clickFlexButton:nil];
    }
}
- (void)clickFlexButton:sender
{
    WK(weakSelf)
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.quickCardIV.alpha = 0.0f;
    } completion:^(BOOL finished) {
        weakSelf.quickCardIV.hidden = YES;
    }];
}
#pragma mark - 客资Cell模块
/**
 1.异步请求客资状态
    未领取
    1.1 发送假客资消息
    领取
 */
- (void)sendGuestMessage
{
    WK(weakSelf)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.storeModel.sellerId forKey:@"sellerId"];
    [parameters setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/secondaryQueryController/findUserInfoAndSellerInfo"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull data) {
        //NSLog(@"%@",data);
        TTIM_UserInfoSellerInfoModel *responModel = [TTIM_UserInfoSellerInfoModel modelWithJSON:data];
        //responModel.data.consultingStar = @"咨询测试王盼盼";
        //responModel.data.arrivalGift = @"到店测试王盼盼";
        //responModel.data.isReceive = @"2";
        if (responModel.success && (responModel.data.consultingStar.length > 0 || responModel.data.arrivalGift.length > 0) && [responModel.data.isReceive isEqualToString:@"2"]) {
            TUICustomModel *customModel = [[TUICustomModel alloc]init];
            TUICustomExtModel *extModel = [[TUICustomExtModel alloc]init];
            customModel.type = 7;
            customModel.ext = extModel;
            extModel.arrivalGift = responModel.data.arrivalGift;
            extModel.consultingStar = responModel.data.consultingStar;
            extModel.cdUserName = responModel.data.userName;
            extModel.cdUserTel = responModel.data.userTel;
            extModel.cdAppointmentTime = responModel.data.cdAppointmentTime;
            
            TUIGuestMessageCellData *cellData = [[TUIGuestMessageCellData alloc] initWithDirection:MsgDirectionOutgoing];
            cellData.customModel = customModel;
            [weakSelf.chat sendMessage:cellData];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}
- (void)TUIGuestMessageCellDelegateBackCell:(TUIGuestMessageCell *)cell backType:(NSInteger)type
{
    WK(weakSelf)
    switch (type) {
        case 0:
        {
            //编辑
            //PackageDetailBottomActionType_yuyue
            StoreDetailSubscribeView *subscribeView = [[NSBundle mainBundle] loadNibNamed:@"StoreDetailSubscribeView"owner:nil options:nil].firstObject;
            subscribeView.frame = CGRectMake(10, 10, TTScreenWidth,300);
            LSTPopView *popView = [LSTPopView initWithCustomView:subscribeView
                                                        popStyle:LSTPopStyleSmoothFromBottom
                                                    dismissStyle:LSTDismissStyleSmoothToBottom];
            popView.hemStyle = LSTHemStyleBottom;
            popView.popDuration = 0.5;
            popView.dismissDuration = 0.5;
            popView.isClickFeedback = YES;
            [popView pop];
            
            self.popView = popView;
            
            LSTPopViewWK(popView)
            [popView setBgClickBlock:^{
                [wk_popView dismiss];
            }];
            
            LSTPopViewWK(subscribeView)
            [subscribeView setStoreDetailSubscribeBlock:^(StoreDetailSubscribeViewActionType type) {
                switch (type) {
                    case StoreDetailSubscribeViewActionType_selTime:
                    {
                        [sharedKeyWindow endEditing:YES];
                        [BRDatePickerView showDatePickerWithMode:BRDatePickerModeYMDHM title:@"选择预约时间" selectValue:@"" minDate:[Utilities getDateWithTimestamp:[Utilities getCurrentTimestamp]] maxDate:[NSDate br_setYear:2050 month:12 day:1] isAutoSelect:NO resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
                            wk_subscribeView.arriveTimeLab.text = selectValue;
                            wk_subscribeView.arriveTimeLab.textColor = UIColorHex(0x333333);
                        }];
                    }
                        break;
                    case StoreDetailSubscribeViewActionType_handle:
                    {
                        NSString *name = wk_subscribeView.nameTF.text;
                        NSString *phone = wk_subscribeView.phoneTF.text;
                        NSString *time = wk_subscribeView.arriveTimeLab.text;
                        
                        cell.guestCellData.customModel.ext.cdUserName = name;
                        cell.guestCellData.customModel.ext.cdUserTel = phone;
                        cell.guestCellData.customModel.ext.cdAppointmentTime = time;
                        cell.guestCellData.customModel = cell.guestCellData.customModel;
                        [cell fillWithData:cell.guestCellData];
                        
                        [wk_popView dismiss];
                        [wk_subscribeView clearView];
                    }
                        break;
                    default:
                        break;
                }
            }];
        }
            break;
        case 1:
        {
            //确定
            if (cell.guestCellData.customModel.ext.cdUserName.length == 0) {
                [SVProgressHUD showWithStatus:@"用户姓名不能为空~"];
                [SVProgressHUD dismissWithDelay:1];
                [self TUIGuestMessageCellDelegateBackCell:cell backType:0];
                return;
            }
            if (cell.guestCellData.customModel.ext.cdUserTel.length == 0) {
                [SVProgressHUD showWithStatus:@"用户联系方式不能为空~"];
                [SVProgressHUD dismissWithDelay:1];
                [self TUIGuestMessageCellDelegateBackCell:cell backType:0];
                return;
            }
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setValue:self.storeModel.sellerId forKey:@"sellerId"];
            [parameters setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
            [parameters setValue:cell.guestCellData.customModel.ext.cdUserTel forKey:@"userTel"];
            [parameters setValue:cell.guestCellData.customModel.ext.cdUserName forKey:@"userName"];
            if (cell.guestCellData.customModel.ext.cdAppointmentTime.length > 0) {
                [parameters setValue:cell.guestCellData.customModel.ext.cdUserName forKey:@"userName"];
            }
            NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/secondaryQueryController/insertUserReceive"];
            [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
                NSLog(@"%@",responseObject);
                BaseResponse *responModel = [BaseResponse modelWithJSON:responseObject];
                if (1) {
                    [SVProgressHUD showWithStatus:@"领取成功"];
                    [SVProgressHUD dismissWithDelay:0.5];
                    //更新当前cell
                    cell.guestCellData.customModel.ext.isReceive = YES;
                    [cell fillWithData:cell.guestCellData];
                    //发送消息 重组数据数据干净些
                    NSMutableDictionary *dic = @{}.mutableCopy;
                    NSMutableDictionary *ext = @{}.mutableCopy;
                    [dic setValue:@(6) forKey:@"type"];
                    [dic setValue:ext forKey:@"ext"];
                    [ext setValue:cell.guestCellData.customModel.ext.arrivalGift forKey:@"arrivalGift"];
                    [ext setValue:cell.guestCellData.customModel.ext.consultingStar forKey:@"consultingStar"];
                    [ext setValue:cell.guestCellData.customModel.ext.cdUserTel forKey:@"cdUserTel"];
                    [ext setValue:cell.guestCellData.customModel.ext.cdUserName forKey:@"cdUserName"];
                    if (cell.guestCellData.customModel.ext.cdAppointmentTime.length > 0) {
                        [ext setValue:cell.guestCellData.customModel.ext.cdAppointmentTime forKey:@"cdAppointmentTime"];
                    }
                    [ext setValue:[NSNumber numberWithBool:YES] forKey:@"isReceive"];
                    NSData *data = [Utilities dataWithDic:dic];

                    //TUIGuestMessageCellData *cellData = [[TUIGuestMessageCellData alloc] initWithDirection:MsgDirectionOutgoing];
                    //cellData.customModel = cell.guestCellData.customModel
                    TUIGuestMessageCellData *cellData = cell.guestCellData;
                    cellData.innerMessage = [[V2TIMManager sharedInstance] createCustomMessage:data];
                    [weakSelf.chat sendMessage:cellData];
                }
            } FailedBlock:^(NSError * _Nonnull error) {
                
            }];
        }
            break;
            
        default:
            break;
    }
}
@end
